31. Valid Month

Valid Month

Question:

Start Quiz:

# -----------
# User Instructions
# 
# Modify the valid_month() function to verify 
# whether the data a user enters is a valid 
# month. If the passed in parameter 'month' 
# is not a valid month, return None. 
# If 'month' is a valid month, then return 
# the name of the month with the first letter 
# capitalized.
#

months = ['January',
          'February',
          'March',
          'April',
          'May',
          'June',
          'July',
          'August',
          'September',
          'October',
          'November',
          'December']
          
def valid_month(month):


# print valid_month("january") 
# => "January"    
# print valid_month("January") 
# => "January"
# print valid_month("foo")
# => None
# print valid_month("")
# => None

User's Answer:

(Note: The answer done by the user is not guaranteed to be correct)

# -----------
# User Instructions
# 
# Modify the valid_month() function to verify 
# whether the data a user enters is a valid 
# month. If the passed in parameter 'month' 
# is not a valid month, return None. 
# If 'month' is a valid month, then return 
# the name of the month with the first letter 
# capitalized.
#

months = ['January',
          'February',
          'March',
          'April',
          'May',
          'June',
          'July',
          'August',
          'September',
          'October',
          'November',
          'December']
          
def valid_month(month):
    month=month.capitalize()
    if month in months:
        return month
    else:
        return None

print valid_month("january") 
# => "January"    
# print valid_month("January") 
# => "January"
# print valid_month("foo")
# => None
# print valid_month("")
# => None

Solution:

INSTRUCTOR NOTE:

Hint: You may want to look into the string.capitalize() function

In this answer video, Steve is using list comprehensions to create the dictionary of month abbreviations.
If we were to translate this code:
month_abbvs = dict((m[:3].lower(),m) for m in months)
it would be:
month_abbvs = {}
for m in months:
month_abbvs[m[:3].lower()] = m
You can read more about list comprehensions here